package com.zhan.rkforum.controller;


import com.zhan.rkforum.bean.DiscussPost;
import com.zhan.rkforum.bean.Page;
import com.zhan.rkforum.service.ElasticSearchService;
import com.zhan.rkforum.service.LikeService;
import com.zhan.rkforum.service.UserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SearchController {

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private ElasticSearchService elasticSearchService;

    @RequestMapping(value = "/search", method = {RequestMethod.GET, RequestMethod.POST})
    public String search(String keyword, Page page, Model model) throws Exception {
        List<DiscussPost> lists = elasticSearchService.search(keyword, page);
        ArrayList<Map<String, Object>> discussPosts = new ArrayList<>();
        if(ObjectUtils.isNotEmpty(lists)){
            for (DiscussPost discussPost : lists) {
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("post", discussPost);
                hashMap.put("user", userService.findUserById(Integer.parseInt(discussPost.getUserId())));
                hashMap.put("likeCount", likeService.getEntityLikeCount(discussPost.getType(), discussPost.getId()));
                discussPosts.add(hashMap);
            }
        }
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("keyword", keyword);

        //设置分页信息

        page.setPath("/search?keyword=" + keyword);

        //page.setRows(lists == null ? 0 : lists.size());

        return "site/search";
    }

}
